# _*_ encoding: utf-8 _*_
"""
@Softwave: Pycharm
@Python: 3.X
@Author: SKYNE
@Contact: 520@skyne.cn
@Time: 2017.10.22
"""

import socket
import string
import random
from time import ctime

class Server():
    def __init__(self, Host, Port):
        self.HOST = Host
        self.PORT = Port
        self.Poll_code = {
            '15031310170':'aski'
        }
        self.BUFF_SIZE = 1024
        self.message = None
    #   此方法可以产生一个随机的四个字母或者数字的字符串
    # def Get_Poll_Code(self):
    #     field = string.ascii_letters + string.digits
    #     Code = random.sample(field, 4)   #随机从field抽取四位
    #     STR = ''
    #     for i in Code:
    #         STR = STR + i
    #     return STR     ##返回一个字符串

    def Socket(self):
        S = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        S.bind((self.HOST, self.PORT))
        S.listen(1)
        print("服务端正在监听中。。。。")
        self.Write_In("Logs.txt", ctime())
        while True:
            conn, addr = S.accept()
            Stu_ID = conn.recv(self.BUFF_SIZE).decode('utf-8')
            Temp = "客户端 {} 已连接！addr:{}".format(Stu_ID, str(addr))
            self.Write_In("Logs.txt", Temp)
            Flag = self.Judge_Exist(Stu_ID)
            if Flag:
                conn.send("您好！ 您的邀请码为:{}, 请牢记!".format(self.Poll_code[Stu_ID]).encode('utf-8'))
                self.message = "Good,已经成功发送邀请码:{}".format(self.Poll_code[Stu_ID])
                print(self.message)
                print(self.Poll_code)
                self.Write_In("Notes.txt" ,str(self.Poll_code))
                conn.close()
            else:
                conn.send("抱歉，{}尚未注册，请注册！".format(Stu_ID).encode('utf-8'))
                print(self.message)
                conn.close()

    def Judge_Exist(self,Stu_ID):
        if Stu_ID in self.Poll_code.keys():
            self.message = "抱歉，您已注册，您的邀请码为：{}".format(self.Poll_code[Stu_ID])
            flag = 1
            return flag
        else:
            self.message = "抱歉，{}尚未注册，请注册！".format(Stu_ID)
            flag = 0
            return flag

    def Write_In(self, File_name,Dict_Char):
        with open(File_name, 'a+') as f:
            f.writelines(Dict_Char)
            f.writelines("\n\n")


if __name__ == '__main__':
    HOST = '127.0.0.1'
    PORT = 3434
    server = Server(Host=HOST, Port=PORT)
    server.Socket()